/** @jsxImportSource @emotion/react */
import type { Meta, StoryObj } from '@storybook/react';
import { fn } from '@storybook/test';
import * as React from "react";
import { Pager} from "../Pager";
// import styles from './styles.module.css'
import { useControls } from 'leva'
import {a, useSpring} from "@react-spring/web";
import {useDrag} from "@use-gesture/react";
import { faker } from '@faker-js/faker/locale/zh_CN';
import {Input, InputGroup, } from "../Form";
import {Vector2} from "@use-gesture/core/dist/declarations/src/types/utils";
import styles from './styles.module.css'
import { TabPanel,  } from "../Tabs";
import {DarkMode, } from "../Theme/Providers";
import {
    IconArrowRight,
} from "../Icons";
import { Text } from "../Text";
import { Button } from "../Button";
import theme from "../Theme";

const meta: Meta<typeof Pager> = {
    title: 'Example/Pager',
    component: Pager,
    parameters: {
        // Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
        layout: 'centered',
    },
    // This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
    tags: ['autodocs'],
    // More on argTypes: https://storybook.js.org/docs/api/argtypes
    argTypes: {
        // backgroundColor: { control: 'color' },
    },
    // Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
    args: { onClick: fn() },
};
export default meta;
type Story = StoryObj<typeof Pager>;
export const 嵌套Div拉拽: Story = {
    args: {
        // elevation: "xl",
    },
    decorators: [
        (Story) => (
            <>
                <ParentSwipe />
            </>
        ),
    ],
};
export const 嵌套PagerpointerMouse: Story = {
    decorators: [
        (Story) => (
                <PagerDraggable />
        ),
    ],
};

// export const TabsExamples = storiesOf("Pager", module)
//   .add("嵌套Div拉拽", () => {
//          return <ParentSwipe />;
//   }).add("嵌套Pager pointerMouse", () => {
//         return <PagerDraggable />;
//     });


function ParentSwipe() {
    const { shown } = useControls({ shown: true })
    return <div className="flex fill center">{shown && <Draggable />}</div>
}

/*原装例子  https://github.com/pmndrs/use-gesture/blob/main/demo/src/sandboxes/gesture-nested/src/App.jsx
改造 和 测试 双层可拉动的Div:
* */
function Draggable() {
    const ref = React.useRef()

    const [color, setColor] = React.useState('black')
    const toggleColor = () => setColor((c) => (c === 'black' ? '#ec625c' : 'black'))

    const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
    const [styleOuter, apiOuter] = useSpring(() => ({ x: 0, y: 0 }))
    const [coords, set] = React.useState({ x: 0, y: 0 })

    const { boundToParent, gesture, ...options } = useControls({
        enabled: true,
        gesture: { options: ['offset', 'movement'] },
        axis: { options: [undefined, 'x', 'y', 'lock'] },
        filterTaps: false,
        boundToParent: false,
        rubberband: false,
        triggerAllEvents: true
    })

    const pointerOptions = useControls('pointer', { touch: false, capture: true, lock: false })

    const bindOuter = useDrag((state) =>{
        const {offset: [x, y] , active, movement: [mx,my], direction: [xDir,yDir] , cancel,
            swipe:[swpx,], last,  canceled,tap, event,intentional } = state;
        console.log("Outer拉动",state,"active",active,"canceled:",canceled,"intentional",intentional);
        event.stopPropagation()    //也加上看
        apiOuter.start({ x, y })
    } )

    // @ts-ignore
    const bind = useDrag(
        (state) => {
            //这里intentional感觉不准确，过滤掉太多了，舍弃掉intentional状态变量。
            const {offset: [x, y] , active, movement: [mx,my], direction: [xDir,yDir] , cancel,
                swipe:[swpx,], last,  canceled,tap, event,intentional } = state;
            event.stopPropagation()    //去掉看
            //   if (intentional) {
            // let [x, y] = state[gesture]
            // set({ x, y })
            //
            // if (pointerOptions.lock) {
            //     const dx = window.innerWidth / 2 - 40
            //     const dy = window.innerHeight / 2 - 40
            //     x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
            //     y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
            // }
            api.start({
                // scale: active ? 1.2 : 1,
                x,
                y,
                // immediate: pointerOptions.lock
            })
            //  }
        },
        {
        }
    )

    return (
        <a.div  {...bindOuter()}  className={styles.hover}  style={styleOuter}

        >
            <div>
                <div>
                    <a.div  {...bind()}  className={styles.drag}  style={style}

                    >
                        <div onClick={toggleColor} style={{ backgroundColor: color }}>
                            <span>bind</span>
                            <span>
                            x:{Math.round(coords.x)}, y:{Math.round(coords.y)}
                        </span>
                        </div>
                    </a.div>
                </div>
            </div>
        </a.div>
    )
}


/*外面Pager 里面再搞个 useDrag测试 双层拉动。
* */
function PagerDraggable() {
    const [form, setForm] = React.useState({ username: "", password: "",
        mobile:''} as any);
    async function doLogin(e: React.FormEvent  | Event)
    {
        console.log("点了form",form);
    }

    const [parentIndex, setParentIndex] = React.useState(0);
    const [childIndex, setChildIndex] = React.useState(0);
    //返回true=脱离控制，交给下一层次的的Pager控制
    const onFatherCannotDrag = React.useCallback(([x, y]:Vector2) => {
        console.log("onFatherCannotDrag跑来  childIndex=",childIndex,"x",x);
        if (x < 0 || x > 0) {
            if (childIndex !== 0) {
                return true;
            }
        }
        return false;
    }, [childIndex]);

    //返回true=脱离控制，交给父辈的Pager控制
    const onCannotDragOver = React.useCallback(([x, y]:Vector2) => {
        console.log("onCannotDragOver来  childIndex=",childIndex,"x",x);
        if (x < 0 || x > 0) {
            if (childIndex > 0) {
                return false;
            }
        }
        return true;
    }, [childIndex]);

    const ref = React.useRef()

    const [color, setColor] = React.useState('black')
    const toggleColor = () => setColor((c) => (c === 'black' ? '#0c625c' : 'pink'))

    const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
    const [styleOuter, apiOuter] = useSpring(() => ({ x: 0, y: 0 }))
    const [coords, set] = React.useState({ x: 0, y: 0 })

    const { boundToParent, gesture, ...options } = useControls({
        enabled: true,
        gesture: { options: ['offset', 'movement'] },
        axis: { options: [undefined, 'x', 'y', 'lock'] },
        filterTaps: true,
        boundToParent: false,
        rubberband: false,
        triggerAllEvents: true
    })

    const pointerOptions = useControls('pointer', { touch: false, capture: false,mouse: true, lock: false })

    const bindOuter = useDrag(({ offset: [x, y] }) => apiOuter.start({ x, y }))

    // @ts-ignore
    const bind = useDrag(
        ({ event, active, intentional, tap, canceled, ...state }) => {
            event.stopPropagation()
            //   if (intentional) {
            let [x, y] = state[gesture]
            set({ x, y })

            if (pointerOptions.lock) {
                const dx = window.innerWidth / 2 - 40
                const dy = window.innerHeight / 2 - 40
                x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
                y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
            }
            api.start({
                scale: active ? 1.2 : 1,
                x: active || gesture === 'offset' ? x : 0,
                y: active || gesture === 'offset' ? y : 0,
                immediate: pointerOptions.lock
            })
            //  }
        },
        {
            ...options,
            pointer: pointerOptions,
            ...(boundToParent && { bounds: ref }),
            // pointer: { mouse: true },    触摸屏 touch: true,mouse: false 电脑屏 touch:false ,mouse: true,
            // triggerAllEvents: true,    电脑屏为了确保serach input cancel触发最好改triggerAllEvents: false,
            // filterTaps: true,
        }
    )

    return (
        <div
            css={{
                width: '100vw',
                height: '100vh',
                borderRadius: 0,
                maxWidth: "100vw",
                overflow: "hidden",
                [theme.mediaQueries.md]: {
                    maxWidth: "450px",
                    borderRadius: theme.radii.lg
                }
            }}
        >
            <Pager  lazyLoad={false}  noBind={false}
                    value={parentIndex}   onRequestChange={i => setParentIndex(i)}
                    onNestDragEnd={onFatherCannotDrag}
                    css={{
                        height: '100%',
                    }}
            >
                <TabPanel id="meisp"
                          css={{
                              height: '100%',
                          }}
                >
                    <div
                        css={{
                            background: theme.colors.palette.green.base,
                            flex: 1,
                            display: "flex",
                            justifyContent: "center",
                            alignItems: "center"
                        }}
                    >
                        <DarkMode>
                            <Text
                                css={{
                                    display: "flex",
                                    height: "300px",
                                    alignItems: "center"
                                }}
                            >
                                <Button
                                    variant="ghost"
                                    onPress={() => setParentIndex(1)}
                                    iconAfter={<IconArrowRight />}
                                >
                                    父辈Pager 第一页View next进去 Son:
                                </Button>
                            </Text>
                        </DarkMode>
                    </div>

                </TabPanel>

                <TabPanel id="subreport"
                          css={{
                              height: '100%',
                          }}
                >
                    <a.div tabIndex={-1} {...bind()}  className={styles.drag}  style={style}

                    >
                        <div onClick={toggleColor} style={{ backgroundColor: color }}>
                            <span>里面嵌套的bind</span>
                            <span>
                                x:{Math.round(coords.x)}, y:{Math.round(coords.y)}
                           </span>
                            <form  method="post"
                                   onSubmit={e =>{ doLogin(e) } }>
                                <div   css={{  marginTop: theme.spaces.md   }}>
                                    <InputGroup  label={"账户"}>
                                        <Input  required  type="search"
                                                onChange={e => {
                                                    setForm({ ...form, username: e.currentTarget.value });
                                                }}
                                                value={form.username}
                                                inputSize="md"
                                                placeholder="账户"
                                        />
                                    </InputGroup>
                                    <div css={{ display: "flex", justifyContent: "flex-end" }}>
                                        <Button
                                            block
                                            component="button"
                                            css={{
                                                textAlign: "center",
                                                width: "100%",
                                                marginTop: theme.spaces.md
                                            }}
                                            type="submit"
                                            size="md"
                                            intent="primary"
                                        >
                                            登录1submit
                                        </Button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </a.div>
                </TabPanel>
            </Pager>
        </div>
    )
}
